<template>
  <!-- 生动化测量 -->
  <HeaderNavTabarVue :title="title" />
  <view class="material-box" :style="'min-height: ' + boxHeight + 'rpx;'">
    <view class="material-list" v-for="(item, index) in materialData" :key="index">
      <view class="list-num">
        <p class="indexHao">第{{ toChineseNumberFn(index + 1) }}项</p>
      </view>
      <view class="list-info">
        <view class="main-content-row">
          <picker
            @change="businessTypeChange($event, index)"
            :value="item.businessType"
            :range="businessTypePicker"
            class="picker-content"
          >
            <view class="measurement-info-list">
              <text class="info-list-left isrequired">业务类型</text>
              <view class="info-list-right">
                <view v-if="item.businessType" class="uni-input">{{ item.businessType }}</view>
                <view class="uni-inputs" v-else>请选择</view>
                <i class="iconfont icon-youjiantou"></i>
              </view>
            </view>
          </picker>

          <MyPicker
            @getVlaue="getValue('productName', index, $event)"
            :ref="(el) => getRiskSpreadRef(el, index)"
            popupTitle="请选择存货名称"
            class="picker-content"
          >
            <view class="measurement-info-list" @tap="toggle('productName', index)">
              <text class="info-list-left isrequired">存货名称</text>
              <view class="info-list-right">
                <view v-if="item.productName" class="uni-input">{{ item.productName }}</view>
                <view class="uni-inputs" v-else>请选择</view>
                <i class="iconfont icon-youjiantou"></i>
              </view>
            </view>
          </MyPicker>

          <view class="picker-content">
            <view class="measurement-info-list">
              <text class="info-list-left isrequired">单位与数量</text>
              <view class="info-list-right">
                <input
                  adjust-position
                  type="number"
                  class="uni-input placeholder-right"
                  placeholder="请输入"
                  v-model="item.totalQuantity"
                  @input="totalQuantityChange(item.totalQuantity, item.unit)"
                />
                <text class="unit"> {{ item.unit }} </text>
              </view>
            </view>
          </view>
          <!-- 校验失败提示 -->
          <view class="error-reg" v-if="!totalQuantityReg"> 请输入有效的正整数 </view>
          <view class="picker-content">
            <view class="measurement-info-list">
              <text class="info-list-left isrequired">长度</text>
              <view class="info-list-right">
                <input
                  adjust-position
                  type="number"
                  class="uni-input placeholder-right"
                  placeholder="请输入"
                  v-model="item.materialHeight"
                />
                <text class="unit">m</text>
              </view>
            </view>
          </view>
          <view class="picker-content">
            <view class="measurement-info-list">
              <text class="info-list-left isrequired">宽度</text>
              <view class="info-list-right">
                <input
                  adjust-position
                  type="number"
                  class="uni-input placeholder-right"
                  placeholder="请输入"
                  v-model="item.materialWidth"
                />
                <text class="unit">m</text>
              </view>
            </view>
          </view>
          <view class="picker-content">
            <view class="measurement-info-list">
              <text class="info-list-left isrequired">件数</text>
              <view class="info-list-right">
                <view class="info-content">
                  <input
                    adjust-position
                    type="number"
                    class="uni-input placeholder-right"
                    placeholder="请输入"
                    v-model="item.quantityPerPiece"
                    @input="quantityPerPieceChange(item.quantityPerPiece)"
                  />
                </view>
              </view>
            </view>
          </view>
          <!-- 校验失败提示 -->
          <view class="error-reg" v-if="!quantityPerPieceReg"> 请输入有效的正整数 </view>
          <view class="picker-content">
            <view class="measurement-info-list">
              <text class="info-list-left isrequired">设计元素</text>
              <view class="info-list-right">
                <view class="info-content">
                  <input
                    adjust-position
                    type="text"
                    class="uni-input placeholder-right"
                    placeholder="请输入"
                    v-model="item.materialDesignElements"
                  />
                </view>
              </view>
            </view>
          </view>
          <view class="picker-content">
            <view class="measurement-info-list">
              <text class="info-list-left">备注</text>
              <view class="info-list-right">
                <view class="info-content">
                  <input
                    adjust-position
                    type="text"
                    class="uni-input placeholder-right"
                    placeholder="请输入"
                    v-model="item.materialRemark"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>

        <view class="box-btn">
          <button
            class="detele-btn"
            @tap="deteleBtn(index)"
            v-if="materialData.length > 1 || index !== 0"
          >
            <i class="iconfont icon-shanchu"></i>
            <text>删除</text>
          </button>
          <button class="copy-btn" @tap="copyBtn(item)">
            <i class="iconfont icon-copy-template"></i>
            <text>复制</text>
          </button>
          <button class="add-btn" @tap="addBtn">
            <i class="iconfont icon-addNode"></i>
            <text>增加</text>
          </button>
        </view>
      </view>
    </view>
    <view class="uploadImage">
      <view class="materialImage-title">
        <h4>上传图片</h4>
        <text>最多上传6张</text>
      </view>
      <view class="materialImage-upload">
        <UploadFile
          @getSuccessUrl="getSuccessUrl"
          :imageList="materialImages"
          @onDelete="onDelete"
        />
      </view>
    </view>
    <view class="subData">
      <button @tap="submitForm">直接提交</button>
    </view>
  </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { addMeasurement, getproductsApi } from '@/api/customer.js'
import { ref, reactive, nextTick } from 'vue'
import { getTitleBarHeight } from '@/utils/system.js'
import { getToken } from '@/utils/auth.js'

import store from '@/store'
import HeaderNavTabarVue from '../../../components/HeaderNavTabar/HeaderNavTabar.vue'
import userToChineseNumber from '@/hook/toChineseNumber.js'
import UploadFile from '@/components/UploadFile/UploadFile.vue'
import config from '@/config.js'
import { isObjectValuesNotEmpty } from '@/utils/objIsnull.js'
import { zzshuRegFn } from '@/utils/reg.js'

const systemInfo = uni.getSystemInfoSync()
const isAndroid = systemInfo.platform.toLowerCase() === 'android'
const boxHeight = (uni.getSystemInfoSync().windowHeight - getTitleBarHeight()) * 2
const { toChineseNumberFn } = userToChineseNumber()
let riskSpreadRefList = ref([])

const title = ref('新建测量单 - 生动化数据')
const isEdit = ref('')
// 页面内容高度
const getRiskSpreadRef = (el, index) => {
  if (el) {
    riskSpreadRefList.value[index] = el
  }
}
// 组合的参数
let apiParams = reactive()
let materialImage = ref([]) // 生动化图片
let materialImages = ref([]) // 生动化图片信息
let productNameList = ref([])
let materialData = reactive([
  {
    businessType: '', // 业务类型
    productId: '', // 存货名称
    productName: '', // 存货名称
    totalQuantity: '', // 数量
    unit: '', // 单位
    materialHeight: '', // 长度
    materialWidth: '', // 宽度
    quantityPerPiece: '', // 件数
    materialDesignElements: '', // 设计元素
    materialRemark: '', // 备注
  },
])
let businessTypePicker = ['物料类', '门头', '装修类', '活动类', '其他']
const deteleBtn = (i) => {
  uni.showModal({
    content: '你确认要删除这条信息吗？',
    success: function (res) {
      if (res.confirm) {
        materialData.splice(i, 1)
      }
    },
  })
}
const copyBtn = (v) => {
  let copyData = JSON.parse(JSON.stringify(v))
  materialData.push(copyData)
}
const addBtn = () => {
  materialData.push({
    businessType: '', // 业务类型
    productId: '', // 存货名称
    productName: '', // 存货名称
    totalQuantity: '', // 数量
    unit: '', // 单位
    materialHeight: '', // 长度
    materialWidth: '', // 宽度
    quantityPerPiece: '', // 件数
    materialDesignElements: '', // 设计元素
    materialRemark: '', // 备注
  })
}
const addMeasurementFn = async (params) => {
  params.mtype = '其他类'
  params.material = isAndroid ? '安卓' : '苹果'
  let { code, msg } = await addMeasurement(params)
  if (code == 200) {
    uni.showToast({
      title: msg,
      icon: 'success',
    })
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/work/index',
      })
    }, 500)
  } else {
    uni.showToast({
      title: '操作失败',
      icon: 'error',
    })
  }
}
// 选择业务类型
const businessTypeChange = ($enent, index) => {
  materialData[index].businessType = businessTypePicker[$enent.detail.value]
}

const getValue = (i, index, $event) => {
  if (i == 'productName') {
    // 选择的存货名称
    materialData[index].productId = $event.value
    materialData[index].productName = $event.label
    materialData[index].unit = $event.unit
    riskSpreadRefList.value[index].closePop()
  }
}
// 打开模态床
const toggle = (i, index) => {
  if (i == 'productName') {
    store.commit('setCustomerList', productNameList.value)
    riskSpreadRefList.value[index].toggle('bottom')
  }
}
// 获取存货下拉菜单数据
const getproductsApiData = async (v = '') => {
  let params = {
    customerName: v,
  }
  let { code, data } = await getproductsApi(params)
  if (code == 200) {
    let customerList = []
    data.forEach((v) => {
      productNameList.value.push({
        label: v.productName,
        value: v.productId,
        unit: v.unit,
      })
    })
  }
}
const getSuccessUrl = (fileName) => {
  materialImage.value.push(config.baseUrl + fileName)
  materialImages.value.push({
    url: config.baseUrl + fileName,
    extname: 'jpeg',
    name: config.baseUrl + fileName,
  })
}
const onDelete = (emit) => {
  materialImage.value = emit
  materialImages.value = emit.map((item, index) => {
    return {
      name: item,
      extname: 'jpeg',
      url: item,
    }
  })
}
const submitForm = () => {
  if (isEdit.value === false) {
    // 详情 点击 直接提交
    uni.showToast({
      title: '只有查看权限,不能提交',
      icon: 'none',
    })
    return
  }
  const RequiredItemList = JSON.parse(JSON.stringify(materialData))
  RequiredItemList.forEach((item) => {
    delete item.materialRemark
  })
  // console.log(RequiredItemList, 'RequiredItemList')
  if (isObjectValuesNotEmpty(RequiredItemList)) {
    apiParams.materialImage = JSON.stringify(materialImage.value)
    apiParams.materialList = JSON.stringify(materialData)
    if (isEdit.value) {
      // 编辑接口
      uni.showToast({
        title: '编辑功能开发中~',
        icon: 'error',
      })
    } else {
      // 新增
      addMeasurementFn(apiParams)
    }
  } else {
    uni.showToast({
      title: '请输入完整数据',
      icon: 'error',
    })
  }
}

const totalQuantityReg = ref(true)
const quantityPerPieceReg = ref(true)
// 校验单位与数量
const totalQuantityChange = (value, unit) => {
  // if(unit === '个' || unit === '卷' || unit === '根' || unit === '支' || unit === '盘'){
  totalQuantityReg.value = zzshuRegFn(value)
  // }
}

// 件数
const quantityPerPieceChange = (value) => {
  quantityPerPieceReg.value = zzshuRegFn(value)
}

onLoad((options) => {
  apiParams = JSON.parse(decodeURIComponent(options.sss))
  getproductsApiData()
  if (options.isEdit) {
    //   编辑 / 详情
    let data = JSON.parse(decodeURIComponent(options.sss))
    materialData = JSON.parse(data.materialList)
    console.log(JSON.parse(data.materialImage), 'materialImage')
    // materialImage.value = JSON.parse(data.materialImage)
    nextTick(() => {
      JSON.parse(data.materialImage).map((item) => {
        materialImages.value.push({
          url: item,
          extname: 'jpeg',
          name: item,
        })
      })
    })
    title.value = JSON.parse(options.isEdit.toLowerCase())
      ? '编辑测量单 - 结构图数据'
      : '查看测量单 - 结构图数据'
    isEdit.value = JSON.parse(options.isEdit.toLowerCase()) // true 编辑 false 详情
  }
})
</script>

<style lang="scss" scoped>
@import '../../../static/style/index.scss';

.material-box {
  padding: $spacing-row-base;
  box-sizing: border-box;
  // @include main-area-bgColor;
  background-color: $uni-bai;
  overflow-y: auto;

  :deep(.uni-input-input) {
    text-align: right;
  }

  .material-list {
    .list-num {
      border-top: 1px solid #e5e6eb;
      position: relative;
      margin: 30px 0;

      .indexHao {
        height: 40rpx;
        width: 160rpx;
        // @include main-area-bgColor;
        background-color: $uni-bai;
        // @include font-color-auxiliary;
        color: $uni-fc-fu-lin;
        position: absolute;
        text-align: center;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: $font-size-sm-base;
      }
    }

    .list-info {
      .main-content-row {
        // @include background-color;
        background-color: $uni-bg-lin;
        border-radius: 16rpx;

        .measurement-info-list {
          @include flex($align: center, $justify: space-between);
          padding: $spacing-row-base;

          .info-list-left {
            // @include font-color-auxiliary;
            color: $uni-fc-fu-lin;
            font-size: $font-size-base;
          }

          .info-list-right {
            @include flex($align: center);

            .info-content {
              @include textStyleBase;
              font-size: 34rpx;
            }

            .iconfont {
              margin-left: 16rpx;
              // @include font-color-auxiliary;
              color: $uni-fc-fu-lin;
            }
          }

          .unit {
            // @include font-color-auxiliary;
            color: $uni-fc-fu-lin;
          }
        }
      }

      .box-btn {
        @include flex(center, space-between);
        height: 68rpx;
        font-size: 26rpx;
        margin-top: $spacing-col-sm;
        margin-bottom: $spacing-row-base;

        button {
          height: 100%;
          line-height: 68rpx;
          color: #fff;
          margin: 0;
          font-size: 26rpx;
          flex: 1;

          .iconfont {
            margin-right: 20rpx;
          }
        }

        .detele-btn {
          background-color: #f53f3f;
          margin-right: 20rpx;
        }

        .copy-btn {
          background-color: $btn-bg-color;
          margin-right: 20rpx;
        }

        .add-btn {
          background-color: $btn-bg-color;
        }
      }
    }
  }

  .uploadImage {
    // @include background-color;
    background-color: $uni-bg-lin;
    padding: $spacing-row-base $spacing-col-base;
    border-radius: 16rpx;

    .materialImage-title {
      @include flex(center, space-between);
      margin-bottom: $spacing-row-base;

      h4 {
        font-weight: 400;
        // @include font-color;
        color: $uni-fc-lin;
      }

      text {
        // @include font-color-auxiliary;
        color: $uni-fc-fu-lin;
      }
    }
  }

  .subData {
    width: 100%;
    margin-top: 40rpx;

    button {
      width: 100%;
      @include btnBg;
    }
  }
}
</style>
